#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <unistd.h>
#include <time.h>
#include "dht.h"


//initialize the required varaibles
struct sockaddr_in this_client_info;
struct sockaddr_in dht_node_info;

int this_node_port_num;
int root_node_port;
int this_client_socket;
int bytes_recieved;

char send_data[1024],recv_data[1024];
char root_node_ip[64];

int main(int argc, char *argv[]){
  	if (argc !=2) {
		
		printf("Usage: \n %s <dhtnode>\n", argv[0]);
		
	} else {
		
	  //	printf("This Node is\t: %i\n", this_node_port_num);
		
	  char node_input[64];
	  char *node_in;
	  
	  strncpy(node_input, argv[1], 64-1);
	  
	    //char *node_input;
	  node_in = strtok(node_input, ":");

	  if(node_in)
	    {
	      strncpy(root_node_ip, node_in, 64-1);
	      printf("Root Node IP\t: %s\n", root_node_ip);
	    }
	  node_in = strtok(NULL, ":");

	  if(node_in) {
	    root_node_port = atoi(node_in);
	    printf("Root Node Port\t: %i\n", root_node_port);
	  }
	  
	  
	  char * s = malloc(3);
	  memcpy(s, "5|", 2);
	  
	  node_connect(root_node_ip,root_node_port, s);
	}
	
}


int node_connect(int dst_ip[64], int dst_port, char send_data[512]){
  //creating socket using TCP
  if ((this_client_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
    perror("Socket Error");
    exit(EXIT_FAILURE);
  }
  
  //dht_node_host = gethostbyname(dst_ip);
  
  this_client_info.sin_family = AF_INET; 
  inet_aton(dst_ip, &(this_client_info.sin_addr)); 
  this_client_info.sin_port = htons(dst_port);
  bzero(&(this_client_info.sin_zero), 8);
  printf("connected...\n");
  
  if (connect(this_client_socket, (struct sockaddr *)&this_client_info,
	      sizeof(struct sockaddr)) == -1)
    {
      perror("Connect Error\t");
      exit(1);
    }
  //closing the node and then close the socket
  send(this_client_socket,send_data,strlen(send_data), 0);   
  close(this_client_socket);
  
    return 0;



	
}
